#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
AI助手API路由
"""

from flask import Blueprint, request, jsonify
from utils import format_response
from decorators import login_required, get_current_user
from services.ai_assistant import AIAssistant
import json

assistant_bp = Blueprint('assistant', __name__)

# 初始化AI助手
ai_assistant = AIAssistant()

@assistant_bp.route('/chat', methods=['POST'])
@login_required
def chat():
    """智能对话"""
    try:
        current_user = get_current_user()
        if not current_user:
            return jsonify(format_response(message="用户未认证", code=401)), 401
        
        data = request.get_json()
        
        message = data.get('message')
        user_context = data.get('context', {})
        
        if not message:
            return jsonify(format_response(message="消息不能为空", code=400)), 400
        
        # 添加用户信息到上下文
        user_context.update({
            'user_id': current_user.id,
            'username': current_user.username,
            'role': current_user.role
        })
        
        result = ai_assistant.chat(message, user_context)
        
        if result['success']:
            # 直接返回AI助手的回复内容
            return jsonify(format_response({
                'response': result.get('response', 'AI助手回复')
            }, "AI助手回复"))
        else:
            return jsonify(format_response(message=result['error'], code=500)), 500
            
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@assistant_bp.route('/code-review', methods=['POST'])
@login_required
def code_review():
    """代码审查"""
    try:
        current_user = get_current_user()
        data = request.get_json()
        
        code = data.get('code')
        language = data.get('language', 'python')
        user_level = data.get('user_level', 'beginner')
        
        if not code:
            return jsonify(format_response(message="代码不能为空", code=400)), 400
        
        result = ai_assistant.code_review(code, language, user_level)
        
        if result['success']:
            return jsonify(format_response(result, "代码审查完成"))
        else:
            return jsonify(format_response(message=result['error'], code=500)), 500
            
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@assistant_bp.route('/learning-guide', methods=['POST'])
@login_required
def learning_guide():
    """学习指导"""
    try:
        current_user = get_current_user()
        data = request.get_json()
        
        topic = data.get('topic')
        user_level = data.get('user_level', 'beginner')
        
        if not topic:
            return jsonify(format_response(message="学习主题不能为空", code=400)), 400
        
        result = ai_assistant.learning_guide(topic, user_level)
        
        if result['success']:
            return jsonify(format_response(result, "学习指导生成完成"))
        else:
            return jsonify(format_response(message=result['error'], code=500)), 500
            
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@assistant_bp.route('/debug-help', methods=['POST'])
@login_required
def debug_help():
    """调试帮助"""
    try:
        current_user = get_current_user()
        data = request.get_json()
        
        error_message = data.get('error_message')
        code = data.get('code', '')
        language = data.get('language', 'python')
        
        if not error_message:
            return jsonify(format_response(message="错误信息不能为空", code=400)), 400
        
        result = ai_assistant.debug_help(error_message, code, language)
        
        if result['success']:
            return jsonify(format_response(result, "调试帮助生成完成"))
        else:
            return jsonify(format_response(message=result['error'], code=500)), 500
            
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@assistant_bp.route('/practice-suggestions', methods=['POST'])
@login_required
def practice_suggestions():
    """练习建议"""
    try:
        current_user = get_current_user()
        data = request.get_json()
        
        user_level = data.get('user_level', 'beginner')
        interests = data.get('interests', [])
        
        result = ai_assistant.practice_suggestions(user_level, interests)
        
        if result['success']:
            return jsonify(format_response(result, "练习建议生成完成"))
        else:
            return jsonify(format_response(message=result['error'], code=500)), 500
            
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@assistant_bp.route('/analyze-code', methods=['POST'])
@login_required
def analyze_code():
    """代码分析"""
    try:
        current_user = get_current_user()
        data = request.get_json()
        
        code = data.get('code')
        language = data.get('language', 'python')
        analysis_type = data.get('analysis_type', 'general')  # general, performance, security, style
        
        if not code:
            return jsonify(format_response(message="代码不能为空", code=400)), 400
        
        # 根据分析类型构建不同的提示词
        if analysis_type == 'performance':
            prompt = f"请分析以下{language}代码的性能问题：\n```{language}\n{code}\n```\n请从时间复杂度、空间复杂度、算法优化等方面进行分析。"
        elif analysis_type == 'security':
            prompt = f"请分析以下{language}代码的安全性问题：\n```{language}\n{code}\n```\n请从输入验证、数据安全、权限控制等方面进行分析。"
        elif analysis_type == 'style':
            prompt = f"请分析以下{language}代码的编程风格：\n```{language}\n{code}\n```\n请从命名规范、代码结构、可读性等方面进行分析。"
        else:
            prompt = f"请全面分析以下{language}代码：\n```{language}\n{code}\n```\n请从正确性、性能、安全性、可读性等方面进行分析。"
        
        # 使用AI助手进行分析
        result = ai_assistant.chat(prompt, {
            'user_id': current_user.id,
            'username': current_user.username,
            'role': current_user.role
        })
        
        if result['success']:
            return jsonify(format_response({
                'analysis': result.get('response', '代码分析结果'),
                'analysis_type': analysis_type,
                'language': language
            }, "代码分析完成"))
        else:
            return jsonify(format_response(message=result['error'], code=500)), 500
            
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@assistant_bp.route('/generate-example', methods=['POST'])
@login_required
def generate_example():
    """生成代码示例"""
    try:
        current_user = get_current_user()
        data = request.get_json()
        
        concept = data.get('concept')
        language = data.get('language', 'python')
        complexity = data.get('complexity', 'simple')  # simple, medium, advanced
        
        if not concept:
            return jsonify(format_response(message="概念不能为空", code=400)), 400
        
        prompt = f"请为'{concept}'这个概念生成一个{complexity}难度的{language}代码示例，包含详细的注释和说明。"
        
        result = ai_assistant.chat(prompt, {
            'user_id': current_user.id,
            'username': current_user.username,
            'role': current_user.role
        })
        
        if result['success']:
            return jsonify(format_response({
                'example': result.get('response', '代码示例'),
                'concept': concept,
                'language': language,
                'complexity': complexity
            }, "代码示例生成完成"))
        else:
            return jsonify(format_response(message=result['error'], code=500)), 500
            
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@assistant_bp.route('/explain-concept', methods=['POST'])
@login_required
def explain_concept():
    """概念解释"""
    try:
        current_user = get_current_user()
        data = request.get_json()
        
        concept = data.get('concept')
        user_level = data.get('user_level', 'beginner')
        
        if not concept:
            return jsonify(format_response(message="概念不能为空", code=400)), 400
        
        prompt = f"请为{user_level}水平的学生详细解释'{concept}'这个概念，包括定义、应用场景、相关示例等。"
        
        result = ai_assistant.chat(prompt, {
            'user_id': current_user.id,
            'username': current_user.username,
            'role': current_user.role
        })
        
        if result['success']:
            return jsonify(format_response({
                'explanation': result.get('response', '概念解释'),
                'concept': concept,
                'user_level': user_level
            }, "概念解释完成"))
        else:
            return jsonify(format_response(message=result['error'], code=500)), 500
            
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@assistant_bp.route('/capabilities', methods=['GET'])
def get_capabilities():
    """获取AI助手功能列表"""
    capabilities = {
        'chat': {
            'name': '智能对话',
            'description': '与AI助手进行智能对话，获得编程帮助',
            'endpoint': '/assistant/chat',
            'method': 'POST'
        },
        'code_review': {
            'name': '代码审查',
            'description': '对代码进行审查，提供改进建议',
            'endpoint': '/assistant/code-review',
            'method': 'POST'
        },
        'learning_guide': {
            'name': '学习指导',
            'description': '为特定主题制定学习计划',
            'endpoint': '/assistant/learning-guide',
            'method': 'POST'
        },
        'debug_help': {
            'name': '调试帮助',
            'description': '分析错误并提供解决方案',
            'endpoint': '/assistant/debug-help',
            'method': 'POST'
        },
        'practice_suggestions': {
            'name': '练习建议',
            'description': '根据用户水平提供练习建议',
            'endpoint': '/assistant/practice-suggestions',
            'method': 'POST'
        },
        'analyze_code': {
            'name': '代码分析',
            'description': '从不同角度分析代码',
            'endpoint': '/assistant/analyze-code',
            'method': 'POST'
        },
        'generate_example': {
            'name': '代码示例',
            'description': '生成特定概念的代码示例',
            'endpoint': '/assistant/generate-example',
            'method': 'POST'
        },
        'explain_concept': {
            'name': '概念解释',
            'description': '详细解释编程概念',
            'endpoint': '/assistant/explain-concept',
            'method': 'POST'
        }
    }
    
    return jsonify(format_response(capabilities, "AI助手功能列表"))
